// components/classic/music/index.js
import { classicBehavior } from '../classic-beh.js'
let mMgr = wx.getBackgroundAudioManager()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [classicBehavior],
  properties: {
    src: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    playing: false,
    pauseUrl: 'images/player@pause.png',
    playUrl: 'images/player@play.png'
  },

  // 组件生命周期函数，在组件实例进入页面节点树时执行
  attached: function() {
    this._recoverPlayingStatus()
    this._monitorSwitch()
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPlay: function(event) {
      if (!this.data.playing) {
        mMgr.src = this.properties.src
        this.setData({
          playing: true,
        })
      } else {
        mMgr.pause()
        this.setData({
          playing: false
        })
      }
    },

    // 重置状态
    _recoverPlayingStatus() {
      if(mMgr.paused) {
        this.setData({
          playing: false
        })
        return
      }
      if(mMgr.src === this.properties.src) {
        this.setData({
          playing: true
        })
      }
    },

    // 播放器状态监听
    _monitorSwitch() {
      mMgr.onPlay(() => {
        this._recoverPlayingStatus()
      })
      mMgr.onPause(() => { 
        this._recoverPlayingStatus()
      })
      mMgr.onStop(() => {
        this._recoverPlayingStatus()
      })
      mMgr.onEnded(() => {
        this._recoverPlayingStatus()
      })
    }
  }
})
